#!/bin/sh
set -e

# VirtualBox Guest Additions
# - this will bail quickly and gracefully if we're not in VBox
if modprobe vboxguest &> /dev/null && modprobe vboxsf &> /dev/null; then
	# fire up VBoxService to do timesync, etc
	VBoxService --disable-automount
	# TODO some testing with VBoxService automount so we can trim down this entire hacky script
	
	mountOptions='defaults,iocharset=utf8'
	if grep -q '^docker:' /etc/passwd; then
		mountOptions="${mountOptions},uid=$(id -u docker),gid=$(id -g docker)"
	fi
	
	# try mounting "$name" (which defaults to "$dir") at "$dir",
	# but quietly clean up empty directories if it fails
	try_mount_share() {
		dir="$1"
		name="${2:-$dir}"
		
		mkdir -p "$dir" 2>/dev/null
		if ! mount -t vboxsf -o "$mountOptions" "$name" "$dir" 2>/dev/null; then
			rmdir "$dir" 2>/dev/null || true
			while [ "$(dirname "$dir")" != "$dir" ]; do
				dir="$(dirname "$dir")"
				rmdir "$dir" 2>/dev/null || break
			done
			
			return 1
		fi
		
		return 0
	}
	
	# bfirsh gets all the credit for this hacky workaround :)
	try_mount_share /Users 'Users' \
		|| try_mount_share /Users \
		|| try_mount_share /c/Users 'c/Users' \
		|| try_mount_share /c/Users \
		|| try_mount_share /c/Users 'c:/Users' \
		|| true
	# TODO replace this whole hacky bit with VBoxService --only-automount
	# (the problem with that being that we can't run VBoxService because the
	#  32bit VBoxService won't work with the 64bit kernel modules, but the 64bit
	#  VBoxService won't work with our 32bit userspace; good times)
fi
